package ipgather.core.proxy.thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.net.Proxy.Type;

import org.apache.http.HttpHost;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import ipgather.entity.Host;

public class ProxyCheck {
	private HttpGet request = new HttpGet("http://www.haosou.com/");
	private String yunpan360valid = "<!DOCTYPE html><html  ><head><meta charset=\"utf-8\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><meta name=\"renderer\" content=\"webkit\"><link rel=\"icon\" href=\"/favicon-16.ico\" sizes=\"16x16\"><link rel=\"icon\" href=\"/favicon-32.ico\" sizes=\"32x32\"><meta name=\"Keywords\" content=\"360云盘,免费网盘,网络硬盘,最安全网盘,最大免费网盘,最快的网络硬盘,最好的网盘,无限空间,同步盘,共享群,文件共享群,外链分享,离线下载,云存储\">";
	private CloseableHttpClient httpClient = null;
	private static URL URL = null;
	
	static{
		try {
			URL = new URL("http://www.haosou.com/");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	
	public ProxyCheck(CloseableHttpClient httpClient){
		this.httpClient = httpClient;
	}

	public boolean checkProxyHost(Host host){
		InetSocketAddress proxyAddr = new InetSocketAddress(host.getHn(), host.getP());
		boolean p = false;
		try {
			URLConnection connection = URL.openConnection(new Proxy(Type.HTTP, proxyAddr));
			connection.setConnectTimeout(1000);
			String content = convertStreamToString(connection.getInputStream());
			System.out.println(content);
			if(0!=connection.getDate()&&content.contains("好搜 — 用好搜，特顺手")){
				p = true;
			}
		} catch (IOException e) {
		}
		return p;
	}
	
	private String convertStreamToString(InputStream is) {
		if (null == is){
			return "";
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line.trim());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();

	}
}
